package com.woniu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.woniu.entity.Dept;
import com.woniu.entity.User;
import com.woniu.entity.UserApprove;
import com.woniu.entity.response.ResponseEntity;
import com.woniu.entity.vo.PageUserApprove;
import com.woniu.service.IUserApproveService;
import com.woniu.service.IUserService;
import com.woniu.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hyl
 * @since 2022-08-28
 */
@RestController
@RequestMapping("/brain/userApprove")
@CrossOrigin(allowCredentials = "true", originPatterns = "*")
@Slf4j
public class UserApproveController {
    @Autowired
    private IUserApproveService userApproveService;
    @Autowired
    private IUserService userService;
    @Value("${approve.credentialPath}")
    private String credentialPath;

    /*/**
     *@description
     *@params [userApprove]
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/30
     */
    @RequestMapping("/apply")
    public ResponseEntity applyUserApprove(@RequestBody UserApprove userApprove) {
        userApprove.setUserApproveStatus(String.valueOf(UserApprove.UNAPPROVED));
        User applier = userApprove.getUser();
        applier = userService.getByUserId(applier.getUserId());
        if (Objects.equals(applier.getUserId(), applier.getDept().getDeptManagerId())) {
            userApprove.setUserApproveStatus(String.valueOf(UserApprove.APPROVED));
            userApprove.setUserApproveDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern(DateUtils.DATETIME_FORMAT)));
        }
        Dept dept = new Dept();
        dept.setDeptId(applier.getDept().getDeptId());
        userApprove.setDept(dept);
        userApprove.setUserApplyDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern(DateUtils.DATETIME_FORMAT)));
        userApprove.setUserApproveFeedback("管理员自审批");
        userApproveService.save(userApprove);
        return ResponseEntity.success(userApprove);
    }

    /*/**
     *@description 审批通过
     *@params []
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/30
     */
    @RequestMapping("/approve/{userApproveId}")
    public ResponseEntity approve(@PathVariable Integer userApproveId) {
        UserApprove userApprove = new UserApprove();
        userApprove.setUserApproveId(userApproveId);
        userApprove.setUserApproveStatus(String.valueOf(UserApprove.APPROVED));
        userApproveService.updateById(userApprove);
        return ResponseEntity.success(null);
    }

    /*/**
     *@description 审批拒绝
     *@params []
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/30
     */
    @RequestMapping("/disApprove")
    public ResponseEntity disApprove(@RequestBody UserApprove userApprove) {
        userApprove.setUserApproveStatus(String.valueOf(UserApprove.DISAPPROVE));
        userApproveService.updateById(userApprove);
        return ResponseEntity.success(null);
    }

    /*/**
     *@description 条件查询userApprove
     *@params
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/30
     */
    @RequestMapping("/list")
    public ResponseEntity getUserApproveByCondition(@RequestBody(required = false) UserApprove userApprove) {
        log.info("111111111111111111111111111111111userApprove{}",userApprove);
        log.info("1111111111111111111111111111111111Objects.isNull(userApprove){}",Objects.isNull(userApprove));
        log.info("1111111111111111111111111111111userApprove.getUser(){}",userApprove.getUser());
        return ResponseEntity.success(userApproveService.getUserAppByAny(userApprove));
    }

    /*/**
     *@description 条件分页查询userApprove
     *@params [pageUserApprove]
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/30
     */
    @RequestMapping("/pageList")
    public ResponseEntity getUserApproveByPage(@RequestBody PageUserApprove pageUserApprove) {
        if (pageUserApprove.getP() == null || pageUserApprove.getP().equals(0)) {
            pageUserApprove.setP(1);
        }
        if (pageUserApprove.getPageSize() == null || pageUserApprove.getPageSize().equals(0)) {
            pageUserApprove.setPageSize(10);
        }
        return ResponseEntity.success(userApproveService.getUserAppByAnyWithPage(pageUserApprove.getP(), pageUserApprove.getPageSize(), pageUserApprove.getUserApprove()));
    }

    /*/**
     *@description 上传审批凭证
     *@params [credential, userApproveId]
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/30
     */
    @RequestMapping("/upload/{userApproveId}")
    public ResponseEntity uploadCredentials(MultipartFile file, @PathVariable Integer userApproveId) {
        String path = credentialPath + "/" + UUID.randomUUID() + Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        try {
            file.transferTo(new File(path));
            UpdateWrapper wrapper = new UpdateWrapper();
            wrapper.eq("user_approve_id", userApproveId);
            UserApprove userApprove = new UserApprove();
            userApprove.setUserApproveCredential(path.substring(path.lastIndexOf("/")));
            userApproveService.update(userApprove, wrapper);
            return ResponseEntity.success(path.substring(path.lastIndexOf("/")));
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.fail("data");
        }
    }

    /*/**
     *@description 根据0 和 1 两个状态查询记录个数
     *@params []
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/31
     */
    @RequestMapping("/count/status")
    public ResponseEntity countByStatus() {
        Map<String, Integer> map = new ConcurrentHashMap<>();
        QueryWrapper wrapper1 = new QueryWrapper();
        wrapper1.eq("user_approve_status", "0");
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_approve_status", "1");
        QueryWrapper wrapper2 = new QueryWrapper();
        wrapper2.eq("user_approve_status", "2");
        map.put("0", (int) userApproveService.count(wrapper1));
        map.put("1", (int) userApproveService.count(wrapper));
        map.put("2", (int) userApproveService.count(wrapper2));
        return ResponseEntity.success(map);
    }

    /*/**
     *@description 根据申请人id查询记录条数
     *@params [userId]
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/31
     */
    @RequestMapping("/count/userId/{userId}")
    public ResponseEntity countByUserId(@PathVariable Integer userId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id", userId);
        return ResponseEntity.success(userApproveService.count(wrapper));
    }

    /*/**
     *@description 根据deptId查询记录条数
     *@params [deptId]
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/31
     */
    @RequestMapping("/count/deptId/{deptId}")
    public ResponseEntity countByDeptId(@PathVariable Integer deptId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("dept_id", deptId);
        return ResponseEntity.success(userApproveService.count(wrapper));
    }

    /*/**
     *@description 根据userAppCategoryId查询记录条数
     *@params [userAppCategoryId]
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/31
     */
    @RequestMapping("/count/userAppCategoryId/{userAppCategoryId}")
    public ResponseEntity countByUserAppCategoryId(@PathVariable Integer userAppCategoryId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_app_category_id", userAppCategoryId);
        return ResponseEntity.success(userApproveService.count(wrapper));
    }
}
